﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;

namespace MoneyWentWhere.Utils.Storage
{
    /// <summary>
    /// XML file format using the DataContractSerializer
    /// </summary>
    /// <typeparam name="DocT"></typeparam>
    public class XmlDataContractFormat<DocT> : FileFormat<DocT>
        where DocT : class, IHasStorageInfo
    {
        public override DocT Load(Stream inStream, string password = null)
        {
            try
            {
                DataContractSerializer s = new DataContractSerializer(typeof(DocT));
                using (XmlReader reader = XmlReader.Create(inStream))
                {
                    return (DocT)s.ReadObject(reader, false);
                }
            }
            catch (SerializationException e)
            {
                throw new InvalidDataException("Invalid data", e);
            }
        }

        public override void Save(DocT document, Stream outStream)
        {
            DataContractSerializer s = GetSerializer();

            XmlWriterSettings settings = new XmlWriterSettings() { Indent = true };
            using (XmlWriter writer = XmlWriter.Create(outStream, settings))
            {
                s.WriteObject(writer, document);
            }
        }

        DataContractSerializer GetSerializer()
        {
            return new DataContractSerializer(typeof(DocT));        
        }
    }
}
